package com.sto.stoapp.activity.administrator;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.StoConfig;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.StoLoginActivity;
import com.sto.stoapp.activity.administrator.system.AdminSystemSettingActivity;
import com.sto.stoapp.adapter.SoleAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.constant.StoFileConstant;
import com.sto.stoapp.db.manager.LoginInfoManager;
import com.sto.stoapp.db.manager.SalesSignNameManager;
import com.sto.stoapp.entity.FunctionEntity;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.listener.StoOnItemClickListener;
import com.sto.stoapp.manager.DownShuRuFa;
import com.sto.stoapp.manager.DownShuRuFa.ExceptionClickListener;
import com.sto.stoapp.util.Action;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseActivity;
import com.sto.stoapp.widget.BaseDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import sto.android.app.StoPdaKeyEvent;


public class StoAdminMainActivity extends BaseActivity {

    private List<Integer> keys = new ArrayList<Integer>();

    private ListView adminList;

    private SoleAdapter soleAdapter;

    private boolean isMainAdmin = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sto_admin_main);
        this.setStoTitle(R.string.administrator);
        System.out.println("admin oncreate");
        // 登入类型,用于后面业务判断是业务员或扫描员类型,管理员...
        // UnifiedStaticType.loginType = BaseMessage.ADMIN_VERSION;
        isMainAdmin = getIntent().getBooleanExtra("type", false);
        initWidget();

        keys.add(R.string.bar_number);
        keys.add(R.string.admin_server_ip);
        keys.add(R.string.site_code_number);
        keys.add(R.string.system_settings);
        keys.add(R.string.factory_preinstall);
        keys.add(R.string.business_preinstall);
        if (isMainAdmin)
            keys.add(R.string.record_search);
        keys.add(R.string.access_control);
        keys.add(R.string.h24_hour_control);
        keys.add(R.string.software_recover);
        keys.add(R.string.lib_versions);

    }

    @Override
    protected void onDestroy() {
        System.out.println("admin onDestroy");
        super.onDestroy();
    }

    private void initWidget() {
        adminList = (ListView) findViewById(R.id.admin_list);
        soleAdapter = new SoleAdapter(this, getResoureList());
        adminList.setAdapter(soleAdapter);

        adminList.setOnItemClickListener(new StoOnItemClickListener(this) {

            @Override
            public void KcOnItemClickListener(AdapterView<?> arg0, View arg1,
                                              int arg2, long arg3) {
                arg1.setSelected(true);
                TextView title = (TextView) arg1.findViewById(R.id.res_test);
                clickItemEvent(title.getText().toString());
            }

        });

    }

    private void clickItemEvent(String title) {

        // 服务器IP
        if (title.equals(getText(R.string.admin_server_ip))) {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setClass(this, AdminServerIpActivity.class);
            startActivity(intent);
        }
        // 服务器端口
        else if (title.equals(getText(R.string.admin_server_port))) {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setClass(this, AdminServerPortActivity.class);
            startActivity(intent);
        }
        // 网点编号
        else if (title.equals(getText(R.string.site_code_number))) {
            if (!StoFilePreference.getInstance(this).getSiteCode()
                    .equals(StoFileConstant.DEFAULT_SITE_CODE)) {
                StringBuffer sb = new StringBuffer();
                sb.append(getText(R.string.site_code_prompt).toString())
                        .append(StoFilePreference.getInstance(this)
                                .getSiteCode()).append("\n")
                        .append(getText(R.string.un_allow_change).toString());
                // new AlertDialog.Builder(this)
                // .setMessage(sb.toString())
                // .setPositiveButton(R.string.confirm,
                // new DialogInterface.OnClickListener() {
                //
                // @Override
                // public void onClick(DialogInterface dialog,
                // int which) {
                // dialog.dismiss();
                // }
                // }).setCancelable(false).show();
                final BaseDialog dialog = new BaseDialog(this);
                dialog.setMessage(sb.toString());
                dialog.show();
                dialog.getvCanncel().setVisibility(View.GONE);
                dialog.getvTitle().setVisibility(View.GONE);
                dialog.getvPresentation().setVisibility(View.GONE);
                dialog.setOnBackClickListener(new OnBackClickListener() {

                    @Override
                    public void onBackClickListener(boolean res) {
                        dialog.dismiss();
                    }
                });
                return;
            }
            Intent intent = new Intent(this, AdminSiteCodeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // GPRS接入点
        else if (title.equals(getText(R.string.gprs_ap))) {
            Intent intent = new Intent();
            ComponentName name = new ComponentName(
                    Action.SYSTEM_SETTINGS_PACKAGE, Action.APN_PACKAGE);
            intent.setComponent(name);
            startActivity(intent);
        }
        // 系统设置
        else if (title.equals(getText(R.string.system_settings))) {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(HomeBroadAction.BROAD_TYPE,
                    HomeBroadAction.ADMINISTRATOR_BROAD);
            intent.setClass(this, AdminSystemSettingActivity.class);
            startActivity(intent);
        }
        // 出厂预设
        else if (title.equals(getText(R.string.factory_preinstall))) {
            final BaseDialog dialog = new BaseDialog(this);
            dialog.setMessage(getText(R.string.factory_preinstall_or)
                    .toString());
            dialog.show();
            dialog.getvPresentation().setVisibility(View.GONE);
            dialog.getvTitle().setVisibility(View.GONE);
            dialog.setOnBackClickListener(new OnBackClickListener() {

                @Override
                public void onBackClickListener(boolean res) {
                    dialog.dismiss();
                    if (res) {
                        StoFilePreference
                                .getInstance(StoAdminMainActivity.this)
                                .clearAllData();
                        StoFilePreference
                                .getInstance(StoAdminMainActivity.this)
                                .setFirstInstall(true);
                        StoFilePreference
                                .getInstance(StoAdminMainActivity.this)
                                .setBootStrap(true);

                        // 清空数据库数据
                        Helper.clearAllData(StoAdminMainActivity.this);
                    }
                }
            });
        }
        //24小时开关
        else if (title.equals(getText(R.string.h24_hour_control))) {
            Intent intent = new Intent(this, Switch24HourActivity.class);
            startActivity(intent);
        }
        // 业务预设
        else if (title.equals(getText(R.string.business_preinstall))) {
            final BaseDialog dialog = new BaseDialog(this);
            dialog.setMessage(getText(R.string.delete_login_info).toString());
            dialog.show();
            dialog.getvPresentation().setVisibility(View.GONE);
            dialog.getvTitle().setVisibility(View.GONE);
            dialog.setOnBackClickListener(new OnBackClickListener() {

                @Override
                public void onBackClickListener(boolean res) {
                    dialog.dismiss();
                    if (res) {
                        LoginInfoManager.getInstance(StoAdminMainActivity.this)
                                .deleteAll();
                        SalesSignNameManager.getInstance(
                                StoAdminMainActivity.this).deleteUserData();
                    }
                }
            });
        }
        // 记录查询
        else if (title.equals(getText(R.string.record_search))) {
            Intent intent = new Intent(this, AdminRecordQueryActivity.class);
            // intent.putExtra("busiType", HomeBroadAction.ADMINISTRATOR_BROAD);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        // 权限控制
        else if (title.equals(getText(R.string.access_control))) {
            Intent intent = new Intent(this, AdminAccessControlActivity.class);
            startActivity(intent);
        }
        // 软件复原
        else if (title.equals(getText(R.string.software_recover))) {
            // 功能未开放
            Helper.showToast(this, getText(R.string.function_unpublish)
                    .toString());
        }
        // 巴枪编号
        else if (title.equals(getText(R.string.bar_number))) {
            View view = LayoutInflater.from(this).inflate(R.layout.alert_edit,
                    null);
            final EditText alertText = (EditText) view
                    .findViewById(R.id.alert_edit);

			/*
             * @修改内容：处理虚拟键盘小退
			 * 
			 * @修改人： mgf
			 */
            closeBoard(alertText);
            alertText.setText(StoFilePreference.getInstance(
                    StoAdminMainActivity.this).getBarCodeNumber());
            alertText.setSelection(alertText.getText().toString().length());

            final BaseDialog dialog = new BaseDialog(this);
            dialog.showLog(view);

            view.findViewById(R.id.yes).setOnClickListener(
                    new StoOnClickListener(this) {

                        @Override
                        public void mHonClick(View view) {
                            dialog.dismiss();
                            if (alertText.getText().toString()
                                    .matches("[0-9]+")) {
                                StoFilePreference.getInstance(
                                        StoAdminMainActivity.this)
                                        .setBarCodeNumber(
                                                alertText.getText().toString());
                                Helper.showToast(
                                        StoAdminMainActivity.this,
                                        StoAdminMainActivity.this.getText(
                                                R.string.save_success)
                                                .toString());
                            } else {
                                Helper.showToast(
                                        StoAdminMainActivity.this,
                                        StoAdminMainActivity.this.getText(
                                                R.string.barcode_error)
                                                .toString());
                            }
                        }
                    });

            view.findViewById(R.id.no).setOnClickListener(
                    new StoOnClickListener(this) {

                        @Override
                        public void mHonClick(View view) {
                            dialog.dismiss();
                        }
                    });

            alertText.setOnKeyListener(new OnKeyListener() {
                private boolean isBackKey;

                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (alertText.isFocused()) {
                        if (event.getAction() == StoPdaKeyEvent.KEYCODE_DPAD_UP) {
                            if (keyCode == StoPdaKeyEvent.KEYCODE_DEL
                                    && alertText.getText().toString().length() == 0) {
                                if (!isBackKey) {
                                    dialog.dismiss();
                                    isBackKey = true;
                                    return true;
                                } else {
                                    isBackKey = false;
                                    return true;
                                }
                            }
                            if (alertText.getText().toString().length() > 0) {
                                isBackKey = true;
                                return true;
                            }
                        }
                        return false;
                    }
                    return false;

                }
            });
        }
        // GPS设置
        else if (title.equals(getText(R.string.gps_settings))) {
            Intent intent = new Intent(this, AdminGpsActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (title.equals(getText(R.string.root_switch))) {
            if (StoConfig.NO_VOID) {
                Helper.showToast(this, "未实现");
            } else {
//				KaicomJNI.getInstance(this).TurnOnOffAdbroot(true);
//				Helper.showToast(this, "root打开，退出该界面自动关闭root");
            }

        }
        // 获取库版本
        else if (title.equals(getText(R.string.lib_versions))) {
            String libVer = "不支持获取版本";
            try {
                if (!StoApplication.DeviceModel_420.equals(new Build().MODEL
                        .trim()))
                    libVer = StoApplication.getStoJni().getJniVer();
            } catch (Exception e) {
                e.printStackTrace();
            }

            Helper.showToast(this, libVer);
        }
        // 升级输入法
        else if (title.equals(getText(R.string.up_shurufa))) {
            final DownShuRuFa downApk = new DownShuRuFa(this,
                    "http://122.224.143.206:8888/DownloadFile/STO/Baiduinput.apk");// http://bcscdn.baidu.com/new-repackonline/baiduinput/AndroidPhone/5.0.1.11/1/1000e/20140731200751/baiduinput_AndroidPhone_5-0-1-11_1000e.apk?response-content-disposition=attachment;filename=baiduinput_AndroidPhone_1000e.apk&response-content-type=application/vnd.android.package-archive
            downApk.startDown();
            downApk.setListener(new ExceptionClickListener() {

                @Override
                public void onExceptionClickListener(final String exception) {
                    downApk.dismiss();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Helper.showToast(StoAdminMainActivity.this,
                                    exception);
                            // getString(R.string.upgrade_failed));
                        }
                    });
                }
            });
        }
        // 巴枪清空
        else if (title.equals(getText(R.string.bar_clear))) {
            // TODO
            if (StoFilePreference.getInstance(StoAdminMainActivity.this)
                    .getSuperAdministrator()) {
                final BaseDialog dialog = new BaseDialog(this);
                dialog.setMessage(getText(R.string.clear_barcode_or).toString());
                dialog.show();
                dialog.getvPresentation().setVisibility(View.GONE);
                dialog.getvTitle().setVisibility(View.GONE);
                dialog.setOnBackClickListener(new OnBackClickListener() {

                    @Override
                    public void onBackClickListener(boolean res) {
                        dialog.dismiss();
                        if (res) {
                            String ip = StoFilePreference.getInstance(
                                    StoAdminMainActivity.this).getServerIp();
                            StoFilePreference.getInstance(
                                    StoAdminMainActivity.this).clearAllData();
                            StoFilePreference.getInstance(
                                    StoAdminMainActivity.this).setServerIp(ip);
                            StoFilePreference.getInstance(
                                    StoAdminMainActivity.this).setFirstInstall(
                                    true);

                            StoFilePreference.getInstance(
                                    StoAdminMainActivity.this).setBootStrap(
                                    true);
                            StoAdminMainActivity.this
                                    .deleteDatabase(UnifiedStaticType.DataBase_Name);
                            Helper.showToast(StoAdminMainActivity.this,
                                    getString(R.string.system_reboot));

                            final Timer mTimer = new Timer();
                            mTimer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    // 重启巴枪
                                    StoApplication.getStoJni().SetSystemReboot();

                                    mTimer.cancel();
                                }
                            }, 1 * 1000, 1 * 1000);
                        }

                    }
                });

            } else {
                Helper.showToast(this,
                        getText(R.string.jurisdiction_not_enough).toString());
            }
        }
        // 硬件测试
        else if (title.equals(getText(R.string.hardware_test))) {

        }
        // soleAdapter.setSelectedItem(StoBaseAdapter.INVALID_ITEM);
    }

    private List<FunctionEntity> getResoureList() {
        List<String> resList = new ArrayList<String>();
        resList.add(getText(R.string.admin_server_ip).toString());
        // resList.add(getText(R.string.admin_server_port).toString());
        resList.add(getText(R.string.site_code_number).toString());

        // System.out.println("pwd:" +
        // StoFilePreference.getInstance(this).getUserType());
        // System.out.println("SuperAdmin:" +
        // DexAppJni.getInstance().getSuperAdministratorKey());

        if (StoFilePreference.getInstance(this).getUserType()
                .equals("sb")) {
            resList.add(getText(R.string.gprs_ap).toString());
        }

        resList.add(getText(R.string.system_settings).toString());
        resList.add(getText(R.string.factory_preinstall).toString());
        resList.add(getText(R.string.business_preinstall).toString());
        if (isMainAdmin)
            resList.add(getText(R.string.record_search).toString());
        resList.add(getText(R.string.access_control).toString());
        resList.add(getString(R.string.h24_hour_control).toString());
        resList.add(getText(R.string.software_recover).toString());
        resList.add(getText(R.string.bar_number).toString());
        resList.add(getText(R.string.gps_settings).toString());
        resList.add(getText(R.string.bar_clear).toString());
        if (StoFilePreference.getInstance(StoAdminMainActivity.this)
                .getSuperAdministrator()) {
            resList.add(getText(R.string.lib_versions).toString());
        }
        if (StoFilePreference.getInstance(StoAdminMainActivity.this)
                .getSuperAdministrator()) {
            resList.add(getText(R.string.root_switch).toString());
        }

        List<FunctionEntity> functionList = new ArrayList<FunctionEntity>();
        for (String res : resList) {
            FunctionEntity entity = new FunctionEntity();
            entity.setTitle(res);
            functionList.add(entity);
        }
        return functionList;
    }

    /**
     * 退回到登入界面
     */
    @Override
    public void onBackPressed() {

        final BaseDialog dialog = new BaseDialog(this);
        dialog.setTitles(this.getText(R.string.change_user).toString());
        dialog.show();
        dialog.getvMessage().setVisibility(View.GONE);
        dialog.getvPresentation().setVisibility(View.GONE);
        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {
                dialog.dismiss();
                if (res) {
                    Intent logoutIntent = new Intent(StoAdminMainActivity.this,
                            StoLoginActivity.class);
                    startActivity(logoutIntent);
                    if (StoConfig.NO_VOID) {
                    } else {
//                        KaicomJNI.getInstance(StoAdminMainActivity.this)
//                                .TurnOnOffAdbroot(false);

                    }

                    finish();
                }

            }
        });

    }

    /**
     * 按键映射 数字键0~9映射（0表示列表第十条数据）
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode >= StoPdaKeyEvent.KEYCODE_0 && keyCode <= StoPdaKeyEvent.KEYCODE_9) {
            clickItemEvent(getString(keys.get(keyCode - StoPdaKeyEvent.KEYCODE_0)));
        }
        return super.onKeyDown(keyCode, event);
    }

}
